-- ============================================
-- ROULETTE - SNOUB CASINO (roue circulaire)
-- Nécessite : Advanced Computer + Advanced Monitor + Wired Modem
-- ============================================

local RED_NUMBERS = {
    [1]=true,[3]=true,[5]=true,[7]=true,[9]=true,[12]=true,[14]=true,[16]=true,
    [18]=true,[19]=true,[21]=true,[23]=true,[25]=true,[27]=true,[30]=true,[32]=true,
    [34]=true,[36]=true,
}

-- Ordre reel des numeros sur une roue europeenne
local WHEEL_ORDER = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,
                      16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26}

local function colorOf(n)
    if n == 0 then return colors.green end
    if RED_NUMBERS[n] then return colors.red end
    return colors.gray
end

local MISE = 1
local bank = dofile("client_solde.lua")
local betType = nil   -- "number" ou "color"
local betValue = nil

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local login = dofile("login.lua")
local player = login.authenticate("Qui joue a la roulette ?")
local points = bank.getBalance(player)

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

-- === GEOMETRIE DE LA ROUE CIRCULAIRE ===
local headerH = 4   -- lignes utilisees par le titre/solde
local footerH = 7   -- boutons ROUGE/NOIR/VERT + messages + instruction

local availableH = h - headerH - footerH
local availableW = w - 6

local RY = math.max(4, math.floor(availableH / 2))
local maxRX = math.floor(availableW / 2)
local RX = math.max(8, math.min(maxRX, RY * 2))
RY = math.floor(RX / 2)  -- garde le meme ratio une fois RX fixe

local cx = math.floor(w / 2)
local cy = headerH + RY + 1

local numberPos = {}  -- numberPos[n] = {x, y, len}

local function computePositions()
    for i = 0, 36 do
        local n = WHEEL_ORDER[i + 1]
        local angle = (2 * math.pi * i / 37) - (math.pi / 2)
        local x = cx + math.floor(RX * math.cos(angle) + 0.5)
        local y = cy + math.floor(RY * math.sin(angle) + 0.5)
        local label = tostring(n)
        numberPos[n] = { x = x, y = y, len = #label }
    end
end
computePositions()

local function drawWheel(highlightNumber)
    for n, pos in pairs(numberPos) do
        local highlight = (n == highlightNumber)
        term.setBackgroundColor(highlight and colors.white or colors.black)
        term.setTextColor(highlight and colors.black or colorOf(n))
        local lx = pos.x - math.floor(pos.len / 2)
        term.setCursorPos(lx, pos.y)
        term.write(tostring(n))
    end
end

-- Boutons de mise exterieure (rouge / noir / vert)
local outsideButtons = {}
local outsideY = cy + RY + 3

local function drawOutsideBets(selected)
    local labels = { "ROUGE", "NOIR", "VERT" }
    local cols = { colors.red, colors.gray, colors.green }
    local btnW = math.floor(w / 3)
    outsideButtons = {}
    for i = 1, 3 do
        local x1 = (i - 1) * btnW + 1
        local x2 = x1 + btnW - 1
        term.setBackgroundColor(selected == i and colors.white or cols[i])
        term.setTextColor(selected == i and colors.black or colors.white)
        for x = x1, x2 do
            term.setCursorPos(x, outsideY)
            term.write(" ")
        end
        local lx = x1 + math.floor((btnW - #labels[i]) / 2)
        term.setCursorPos(lx, outsideY)
        term.write(labels[i])
        outsideButtons[i] = { x1 = x1, x2 = x2, y = outsideY, name = labels[i] }
    end
end

local function drawFrame(message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== SNOUB CASINO ===", colors.yellow)
    centerText(2, "ROULETTE - " .. player, colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    drawWheel(nil)
    drawOutsideBets(nil)
    local msgY = outsideY + 2
    if message then
        centerText(msgY, message, msgColor or colors.white)
    end
    centerText(h, "Touche un numero OU une couleur pour miser", colors.lightGray)
end

-- Anime la bille qui tourne autour de la roue
local function spinBall()
    local startIdx = math.random(1, #WHEEL_ORDER)
    local steps = 30 + math.random(0, 10)
    local finalNumber

    for step = 1, steps do
        local idx = ((startIdx + step - 2) % #WHEEL_ORDER) + 1
        local n = WHEEL_ORDER[idx]
        drawWheel(n)
        centerText(outsideY + 2, "La bille tourne...", colors.yellow)
        finalNumber = n
        sleep(0.03 + (step / steps) * 0.15)
    end

    return finalNumber
end

local function payout(number)
    if betType == "number" then
        if betValue == number then return MISE * 35 end
        return 0
    elseif betType == "color" then
        local resultColorName
        if number == 0 then resultColorName = "VERT"
        elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
        else resultColorName = "NOIR" end

        if betValue == resultColorName then
            if resultColorName == "VERT" then return MISE * 14 end
            return MISE * 2
        end
        return 0
    end
    return 0
end

local function playRound()
    if points < MISE then
        drawFrame("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    if not betType then
        drawFrame("Choisis d'abord une mise !", colors.orange)
        sleep(1.5)
        return
    end

    points = points - MISE
    local newBal1 = bank.addBalance(player, -MISE)
    points = newBal1 or points

    drawFrame("Mise placee, la roue tourne...", colors.yellow)
    sleep(0.4)

    local number = spinBall()
    local gain = payout(number)
    local newBal2 = bank.addBalance(player, gain)
    points = newBal2 or (points + gain)

    local resultColorName
    if number == 0 then resultColorName = "VERT"
    elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
    else resultColorName = "NOIR" end

    drawWheel(number)
    local msg = "Resultat : " .. number .. " (" .. resultColorName .. ")"
    centerText(outsideY + 2, msg, colors.white)
    if gain > 0 then
        centerText(outsideY + 3, "GAGNE ! +" .. gain, colors.lime)
    else
        centerText(outsideY + 3, "Perdu... reessaie !", colors.red)
    end
    sleep(2.5)

    betType, betValue = nil, nil
end

-- === PROGRAMME PRINCIPAL ===
drawFrame()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")

    local clickedNumber = nil
    for n, pos in pairs(numberPos) do
        local lx = pos.x - math.floor(pos.len / 2)
        if x >= lx and x <= lx + pos.len - 1 and y == pos.y then
            clickedNumber = n
            break
        end
    end

    if clickedNumber ~= nil then
        betType, betValue = "number", clickedNumber
        drawFrame("Mise sur le " .. clickedNumber .. " (x35)", colors.yellow)
        drawWheel(clickedNumber)
        sleep(0.6)
        playRound()
        drawFrame()
    else
        for i, btn in pairs(outsideButtons) do
            if x >= btn.x1 and x <= btn.x2 and y == btn.y then
                betType, betValue = "color", btn.name
                drawFrame("Mise sur " .. btn.name .. " (x2 ou x14)", colors.yellow)
                drawOutsideBets(i)
                sleep(0.6)
                playRound()
                drawFrame()
                break
            end
        end
    end
end